﻿package game.breeze.message.codec;

import game.breeze.message.AppMessage;
import game.breeze.message.Message;
import game.breeze.socket.util.BufferWrapper;
import game.breeze.socket.util.ByteBuffer;
import game.breeze.socket.util.ByteBufferWrapper;

/**
 * 
 * Class desc there
 * 
 * @author yangwei ywengineer@gmail.com
 * 
 */
public class AppMessageEncoder implements IMessageEncoder<Message, BufferWrapper> {
	public BufferWrapper encode(Message msg) {
		AppMessage appMsg = (msg == null) ? AppMessage.NULL_MESSAGE : (AppMessage) msg;
		BufferWrapper buffer = new ByteBufferWrapper();
		int type = appMsg.getType();
		ByteBuffer msgBuffer = appMsg.getBuffer();
		int length = msgBuffer == null ? 0 : msgBuffer.available();

		buffer.writeInt(type);
		buffer.writeInt(length);

		if (msgBuffer != null) {
			buffer.put(msgBuffer.getRawBytes(), 0, length);
		}

		return buffer;
	}
}